<template>
  <!-- @vue-ignore -->
  <ElTable
    :class="[
      bem.b(),
      bem.is('border', $props.border),
      bem.is('shadow', $props.shadow),
    ]"
    :data="tableData"
    row-key="__id__"
    :expand-row-keys="context.expandedKeys.value"
    @expand-change="handleExpand"
  >
    <slot></slot>
  </ElTable>
  <!-- <ul>
    <li v-for="row in tableData">{{ row }}</li>
  </ul> -->

  <!-- {{ context.expandedKeys }} -->
</template>

<script lang="ts" setup>
import { ElTable } from 'element-plus';
import { nextTick, provide } from 'vue';
import {
  props,
  emits,
  useEasyTableContext,
  easyTableContextKey,
} from './easy-table';
import type { DataSourceItem } from './data-source';
import { createNamespace } from '../../extra-table/src/libs/bem';

defineOptions({ name: 'EasyTable' });
const bem = createNamespace('easy-table');

const $props = defineProps(props);
const $emits = defineEmits(emits);

const context = useEasyTableContext($props, $emits);

const handleExpand = (
  currentRow: DataSourceItem,
  expandedRows: DataSourceItem[]
) => {
  const isExpand = expandedRows.includes(currentRow);
  const rowIndex = context.dataSource.indexOf(currentRow);
  const data = {
    row: currentRow,
    index: rowIndex,
    data: expandedRows,
  };

  nextTick(() => {
    const extraContext = context.getExtra(currentRow.__id__);
    if (isExpand) {
      // context.expand(data, extraContext);
      context.expand(data);
    } else {
      context.shrink(data, extraContext);
    }
  });
};

const { tableData } = context;
provide(easyTableContextKey, context);

defineExpose({
  // addItem: context.addItem,
  add: context.add,
});
</script>

<style>
@import url(./style.scss);
</style>
